<template>
  <div class="page_main">
    <div class="search-box">
      <el-form ref="searchForm" :inline="true" size="mini" :model="searchForm">
        <search-form-box :show-more-btn="true">
          <template slot="showSearch">
            <el-form-item label="项目：" prop="customer_id">
              <el-select v-model="searchForm.customer_id" filterable clearable placeholder="请选择项目"
                         style="width: 240px"
              >
                <el-option v-for="item in customer_arr" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
            <el-form-item label="合同编号：" prop="contract_num">
              <el-input v-model="searchForm.contract_num" filterable clearable placeholder="请输入合同编号"
                        style="width: 240px"
              >
              </el-input>
            </el-form-item>
          </template>
          <template slot="hideSearch">
            <el-form-item label="合同开始时间：" prop="contract_begin_date_start">
              <el-date-picker v-model="searchForm.contract_begin_date_start" type="date" placeholder="合同开始时间"
                              value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="至" prop="contract_begin_date_end">
              <el-date-picker v-model="searchForm.contract_begin_date_end" type="date" placeholder="选择日期"
                              value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="合同结束时间：" prop="contract_end_date_start">
              <el-date-picker v-model="searchForm.contract_end_date_start" type="date" placeholder="合同开始时间"
                              value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="至" prop="contract_end_date_end">
              <el-date-picker v-model="searchForm.contract_end_date_end" type="date" placeholder="选择日期"
                              value-format="yyyy-MM-dd" format="yyyy年MM月dd日" style="width: 180px"
              />
            </el-form-item>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetForm('searchForm')">重置</el-button>
              <el-tooltip effect="dark" content="按照当前筛选条件导出" placement="top">
                <el-button type="success" @click="exportExcel">导出</el-button>
              </el-tooltip>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <div class="table-box">
      <el-table ref="table" v-loading="tableLoading" :data="tableData" size="mini" border :max-height="maxHeight"
                :span-method="arraySpanMethod"
      >
        <el-table-column type="index" label="序号" width="50" fixed="left" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同类别" width="120" align="center" fixed="left">
          <template slot-scope="{row}">
            <el-tag v-if="row.type === 1" type="success" size="mini">现金</el-tag>
            <el-tag v-else-if="row.type === 2" type="primary" size="mini">置换</el-tag>
            <el-tag v-else type="warning" size="mini">半现金半置换</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="industry_name" label="行业" width="150" fixed="left" align="center"/>
        <el-table-column label="合同时间" width="180" align="center" fixed="left">
          <template slot-scope="scope">
            <el-tag size="mini">
              {{
                scope.row.contract_begin_date ? scope.row.contract_begin_date + '~' + scope.row.contract_end_date : ''
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行周期" width="180" align="center" fixed="left">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.begin_date" size="mini">
              {{
                scope.row.begin_date ? scope.row.begin_date + '~' + scope.row.end_date : ''
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="party_a" label="合同名称" width="200" align="center"/>
        <el-table-column label="项目名称" prop="customer_name" width="200" align="center"></el-table-column>
        <el-table-column label="公司抬头" prop="company_head" width="200" align="center"></el-table-column>
        <el-table-column prop="contract_num" label="合同编号" width="200" align="center"/>
        <el-table-column label="合同是否收回并上传" width="150" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.receive_contract ? '是' : '否' }}</span>
            <div v-if="!scope.row.receive_contract">
              <el-button size="mini" type="success" @click="receiveContract(scope.row)"
              >收到合同
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合同入档编号" width="200" align="center">
          <template slot-scope="{row}">
            <div v-if="row.edit">
              <el-input v-model="row.contract_filing_no_back" size="mini" placeholder="请输入合同入档编号" clearable
              ></el-input>
              <div>
                <el-button type="text" @click="fill(row)">保存</el-button>
                <el-button type="text" @click="cancel(row)">取消</el-button>
              </div>
            </div>
            <div v-else>
              {{ row.contract_filing_no }}
              <div>
                <el-button type="text" @click="row.edit = true">修改</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户负责人" prop="person_in_charge_name" width="100" align="center">
        </el-table-column>
        <el-table-column label="维护人" prop="maintenance_staff_name" width="100" align="center">
        </el-table-column>
        <el-table-column prop="group_name" label="组名称" width="200" align="center">
			<template slot-scope="scope">
			  <span>{{ scope.row.group_name }}</span>
			  <div v-if="!!scope.row.group_id && scope.row.group_id != -1">
				  <el-button size="mini" type="primary" @click="editGroup(scope.row)">修改分组</el-button>
			  </div>
			</template>
        </el-table-column>
        <el-table-column label="到款" width="250" align="center">
          <template slot-scope="{row}">
            <span v-if="row.accountReceived">{{
                row.accountReceived.account_received_time
              }}(￥{{ row.accountReceived.account }})</span>
          </template>
        </el-table-column>
        <el-table-column label="媒体形式" width="250" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.itemMediaPrice" :key="index">
              <span>{{ item.media_type_spec_price_name }}：{{ item.count + '个' }}(￥{{ item.price }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="本次执行数量" prop="media_count" width="200" align="center">
        </el-table-column>
        <el-table-column label="刊例总价" width="200" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.mediaPriceList" :key="index">
              <span>{{ item.media_type_spec_price_name }}：{{ item.count + '个' }}(￥{{ item.price }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="折扣" prop="discount" align="center" width="100">
          <template slot-scope="scope">
              <span>
                {{
                  scope.row.discount ? scope.row.discount + '%' : ''
                }}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="本次执行单价" prop="media_price" align="center" width="200">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.mediaPriceList" :key="index">
              <span>{{ item.media_type_spec_price_name }}(￥{{ item.price }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合同金额" prop="contract_amount" width="100" align="center">
        </el-table-column>
        <el-table-column label="本次分项执行金额" width="250" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.itemMediaPrice" :key="index">
              <span>{{ item.media_type_spec_price_name }}：{{ item.count + '个' }}(￥{{ item.price }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="本次执行总金额" prop="execute_amount" align="center" width="100">
        </el-table-column>
        <el-table-column label="现金金额" prop="displace_amount" align="center" width="100">
        </el-table-column>
        <el-table-column label="物品金额" prop="displace_consume_amount" align="center" width="100">
        </el-table-column>
        <el-table-column label="已执行金额" prop="executed_amount" align="center" width="100">
        </el-table-column>
        <el-table-column label="未执行金额" align="center" width="130">
          <template slot-scope="{row}">
            <div>{{ row.unExecuted_amount }}</div>
            <el-button v-if="row.unReceived_amount>0&&row.group_id>0" size="mini" type="success" @click="remind(row)">
              发起收款提醒
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="是否开票" align="center" width="100">
          <template slot-scope="scope">
			  <p style="margin:0"><span>{{ scope.row.invoice_make_out ? '是' : '否' }}</span></p>
			  <p style="margin:0" v-if="scope.row.invoice_make_out"><span :class="[scope.row.group_invoice_received ? 'text-green' : 'text-gray']">
				{{scope.row.group_invoice_received ? '销售已收' : '销售未收'}}</span></p>
          </template>
        </el-table-column>
        <el-table-column label="开票明细" align="center">
          <el-table-column label="开票金额" prop="invoice_amount" align="center" width="100">
          </el-table-column>
          <el-table-column label="开票类目" prop="invoice_category_name" align="center" width="100">
          </el-table-column>
          <el-table-column label="开票增项" prop="additional_amount" align="center" width="100">
          </el-table-column>
        </el-table-column>
        <el-table-column label="往年已收现金金额" prop="amount_received_in_previous_years" width="100" align="center">
        </el-table-column>
        <el-table-column label="往年已收置换物品金额" prop="displace_amount_from_previous_years" width="100"
                         align="center"
        >
        </el-table-column>
        <el-table-column label="往年已收置换消费金额" prop="displace_consume_amount_from_previous_years" width="100"
                         align="center"
        >
        </el-table-column>
        <el-table-column :label="year+'收款信息'" align="center">
          <el-table-column label="已收现金金额" prop="amount_this_year" width="150" align="center">
          </el-table-column>
          <el-table-column label="已收置换物品金额" prop="displace_amount_this_year" width="150" align="center">
          </el-table-column>
          <el-table-column label="已收置换消费金额" prop="displace_consume_amount_this_year" width="150" align="center">
          </el-table-column>
          <el-table-column label="增项金额" prop="additional_amount_this_year" width="150" align="center">
          </el-table-column>
          <el-table-column label="应收现金金额" prop="amount_of_cash_receivable_for_this_year" width="150"
                           align="center"
          >
          </el-table-column>
          <el-table-column label="应收置换物品金额" prop="amount_of_replacement_consumption_receivable_this_year"
                           width="150" align="center"
          >
          </el-table-column>
          <el-table-column label="应收置换消费金额" prop="amount_replacement_receivable_this_year" width="150"
                           align="center"
          >
          </el-table-column>
        </el-table-column>
        <el-table-column label="结算材料" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.has_material ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计收款时间" prop="collection_time" align="center" width="100"></el-table-column>
        <el-table-column label="最新收款时间" prop="latest_collection_time" align="center" width="250">
          <template slot-scope="{row}">
            <div v-if="row.edit_date">
              <el-date-picker
                size="mini"
                v-model="row.latest_collection_time_back"
                type="date"
                placeholder="收款时间"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
              <div>
                <el-button type="text" @click="updateDate(row)">保存</el-button>
                <el-button type="text" @click="cancelDate">取消</el-button>
              </div>
            </div>
            <div v-else>
              {{ row.latest_collection_time }}
              <div>
                <el-button v-if="row.group_id" type="text" @click="row.edit_date = true">修改</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="计提额" prop="accrued_amount" align="center" width="100"></el-table-column>
        <el-table-column label="实际计提额" prop="actual_accrued_amount" align="center" width="100"></el-table-column>
        <el-table-column label="代理资源费" prop="proxy_resource_amount" align="center" width="100"
        ></el-table-column>
        <el-table-column label="物料成本" prop="material_cost" align="center" width="100"></el-table-column>
        <el-table-column label="本年业务费" prop="material_cost" align="center" width="100"></el-table-column>
        <el-table-column label="提成" prop="commission" align="center" width="100"></el-table-column>
        <el-table-column label="公司维护费" prop="company_maintenance_fee" align="center" width="100"
        ></el-table-column>
        <el-table-column label="客户维护费" prop="customer_maintenance_fees" align="center" width="100"
        ></el-table-column>
      </el-table>
    </div>
    <el-pagination :current-page.sync="searchForm.page" :page-sizes="[10,20,50,100, 200,400]"
                   layout="total, sizes, prev, pager, next, jumper" :page-size.sync="searchForm.page_size"
                   :total="total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange"
    />

	<relation-group-dialog ref="RelationGroupDialogRef" isEdit @relationSubmitted="getList"></relation-group-dialog>
  </div>
</template>

<script>
import { exportExcel, fill, list, receiveContract, remind, updateDate } from '@/api/contract_manage'
import { company_list_all } from '@/api/customer/customer'
import SearchFormBox from '@/components/SearchFormBox/index.vue'
import RelationGroupDialog from '@/views/business/sale_order/components/RelationGroupDialog.vue';

export default {
  name: 'NewContractManage',
  components: { SearchFormBox, RelationGroupDialog },
  data() {
    return {
      searchForm: {
        page: 1,
        page_size: 10,
        customer_id: null,
        contract_begin_date_start: null,
        contract_begin_date_end: null,
        contract_end_date_start: null,
        contract_end_date_end: null,
        contract_num: null
      },
      listParams: {
        page: 1,
        page_size: 10,
        customer_id: null,
        contract_begin_date_start: null,
        contract_begin_date_end: null,
        contract_end_date_start: null,
        contract_end_date_end: null,
        contract_num: null
      },
      tableLoading: false,
      tableData: [],
      total: 0,
      customer_arr: [],
      year: '',
      maxHeight: 0
    }
  },
  created() {
    const now = new Date()
    this.year = now.getFullYear()
    this.maxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
    this.getList()
    this.initCustomerArr()
  },
  methods: {
	  editGroup(row){
		  console.log(row);
		  this.$refs.RelationGroupDialogRef.openThis({
			  customer_id: row.customer_id,
		  	edit_group_id: row.group_id,
		  	edit_group_name: row.group_name,
			type: 2
		  });
	  },
    getList() {
      this.listParams = Object.assign({}, this.searchForm)
      this.tableLoading = true
      list(this.listParams).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        // 利用map找出跨行数
        let map = new Map()
        let group_map = new Map()
        this.tableData.forEach(item => {
          this.$set(item, 'contract_filing_no_back', item.contract_filing_no)
          this.$set(item, 'edit', false)
          this.$set(item, 'latest_collection_time_back', item.latest_collection_time)
          this.$set(item, 'edit_date', false)
          if (map.has(item.id)) {
            map.set(item.id, map.get(item.id) + 1)
          } else {
            map.set(item.id, 1)
          }
          let key = item.id + '_' + item.group_id
          if (group_map.has(key)) {
            group_map.set(key, group_map.get(key) + 1)
          } else {
            group_map.set(key, 1)
          }
        })
        this.tableData.forEach(item => {
          if (map.has(item.id)) {
            item.span = [map.get(item.id), 1]
            map.delete(item.id)
          } else {
            item.span = [0, 0]
          }
          let key = item.id + '_' + item.group_id
          if (group_map.has(key)) {
            item.group_span = [group_map.get(key), 1]
            group_map.delete(key)
          } else {
            item.group_span = [0, 0]
          }
        })
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.table.doLayout()
            this.tableLoading = false
          }, 1000)
        })
      }).catch(() => {
        this.tableLoading = false
        this.tableData = []
      })
    },
    search() {
      this.searchForm.page = 1
      this.getList()
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.getList()
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    initCustomerArr() {
      company_list_all({}).then(res => {
        this.customer_arr = res.data
      })
    },
    showBillSaleGroupListDialog(row) {
      this.title = row.party_a + '——' + row.contract_filing_no + ('(此处是合同名称加上归档编号)')
      this.contract_id = row.id
      this.$refs.dialog.show()
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      /**
       * 序号_0                      序号 0       *
       *  行业_1                    合同类别 1    *
       *  合同时间_2                  行业 2      *
       *  执行时间_3                  合同时间 3  *
       *  合同名称_4                  执行时间 4  *
       *  项目名称_5                  合同名称 5  *
       *  公司抬头_6                  项目名称 6  *
       *  合同编号_7                  公司抬头 7  *
       *  合同是否收回并上传_8                 合同编号 8   *
       *  客户负责人_9                 合同是否收回并上传 9  *
       *  维护人_10                  合同入档编号 10       *
       *  组名称_11  sale                  客户负责人 11  *
       *  到款详情_12 sale                  维护人 12   *
       *  已执行金额_21 sale                 组名称 13   sale
       *  未执行金额_22 sale                 到款详情 14 sale
       *  是否开票_23 sale
       *  开票金额_24 sale
       *  开票类目_25 sale
       *  开票增项_26 sale
       *  最新收款时间_29 sale
       *  计提额_30 sale                 合同金额 20 *
       *  实际计提额_31 sale
       *  公司维护费_35 sale
       *  客户维护费_36 sale
       *  合同金额_37
       *  往年已收现金金额_38                 已执行金额 25 sale
       *  往年已收置换物品金额_39                 未执行金额 26  sale
       *  往年已收置换消费金额_40                 是否开票 27  sale
       *  已收现金金额_41                 开票金额 28   sale
       *  已收置换物品金额_42                 开票类目 29  sale
       *  已收置换消费金额_43                 开票增项 30  sale
       *  增项金额_44                 往年已收现金金额 31  *
       *  应收现金金额_45                 往年已收置换物品金额 32  *
       *  应收置换物品金额_46                 往年已收置换消费金额 33  *
       *  应收置换消费金额_47                 已收现金金额 34  *
       *  收款提醒_49 sale                  已收置换物品金额 35  *
       *  合同入档编号_48                 已收置换消费金额 36   *
       *  操作_50                 增项金额 37             *
       * @type {*[]}                  应收现金金额 38   *
       *
       *                            应收置换物品金额 39 *
       *                            应收置换消费金额 40 *
       *
       *
       *                            最新收款时间 43  sale
       *                            计提额 44  sale
       *                            实际计提额 45  sale
       *
       *
       *
       *
       *                            公司维护费 50 sale
       *                            客户维护费 51 sale
       */
      const sale_arr = [13, 25, 26, 27, 28, 29, 30, 43, 44, 45, 50, 51]
      const arr = [0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 20, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
      if (arr.includes(columnIndex)) {
        return row.span === undefined ? [1, 1] : row.span
      } else if (sale_arr.includes(columnIndex)) {
        return row.group_span === undefined ? [1, 1] : row.group_span
      } else {
        return [1, 1]
      }
    },
    receiveContract(row) {
      this.$confirm('是否确认收到合同', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        receiveContract({ id: row.id }).then(res => {
          this.$message.success('操作成功')
          this.getList()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    fill(row) {
      const loading = this.$loading({
        lock: true,
        text: '操作中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      fill({ id: row.id, no: row.contract_filing_no_back }).then(res => {
        this.$message.success('操作成功')
        this.getList()
        loading.close()
        row.edit = false
      }).catch(() => {
        loading.close()
      })
    },
    cancel(row) {
      row.contract_filing_no_back = row.contract_filing_no
      row.edit = false
    },
    cancelDate(row) {
      row.latest_collection_time_back = row.latest_collection_time
      row.edit_date = false
    },
    updateDate(row) {
      const loading = this.$loading({
        lock: true,
        text: '操作中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      updateDate({ group_id: row.group_id, date: row.latest_collection_time_back }).then(res => {
        this.$message.success('操作成功')
        this.getList()
        loading.close()
        row.edit_date = false
      }).catch(() => {
        loading.close()
      })
    },
    remind(row) {
      this.$confirm('是否发起收款催收提醒', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        remind({ id: row.id, group_id: row.group_id }).then(res => {
          this.$message.success('操作成功')
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    exportExcel() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      exportExcel(this.searchForm).then(res => {
        loading.close()
        this.$message.success('导出成功')
      }).catch(() => {
        loading.close()
      })
    }
  }
}
</script>

<style scoped>
.page_main {
  padding: 20px;
}
</style>
